# -*- coding: utf-8 -*-
import json
import os
import re
import chardet
import sys


class TaskInit:

    def __init__(self):
        super().__init__()
        self.init_data = self.red_init_param_file()
        self.load_url_params()
        self.load_db_params()
        self.load_wt_params()
        self.load_ws_params()
        self.init_stream_data()
        self.load_create_datasource_data()

    def getdb_test(self):
        return self.init_data["create_db_data"]

    def load_create_datasource_data(self):
        """
        加数据库文件
        :return:
        """
        self.create_db_data = self.init_data["create_db_data"]

    def load_url_params(self):
        """
        加载数据文件，例：self.headers = self.init_data["url_init"]["headers"]
        :return:
        """
        self.headers = self.init_data["url_init"]["headers"]
        self.login_url = self.init_data["url_init"]["login_url"]
        self.ws_run_url = self.init_data["url_init"]["ws_run_url"]
        self.wt_run_url = self.init_data["url_init"]["wt_run_url"]
        self.wt_stop_url = self.init_data["url_init"]["wt_stop_url"]
        self.wt_search_url = self.init_data["url_init"]["wt_search_url"]
        self.wt_search_27_url = self.init_data["url_init"]["wt_search_27_url"]
        self.ws_workflow_define_url = self.init_data["url_init"]["ws_workflow_define_url"]
        self.ws_workflow_batch_url = self.init_data["url_init"]["ws_workflow_batch_url"]
        self.wt_task_definition_url = self.init_data["url_init"]["wt_task_definition_url"]
        self.wt_import_url = self.init_data["url_init"]["wt_import_url"]
        self.wt_bath_task_instance_url = self.init_data["url_init"]["wt_bath_task_instance_url"]
        self.wt_stream_task_instance_url = self.init_data["url_init"]["wt_stream_task_instance_url"]
        self.wt_database_table_url = self.init_data["url_init"]["wt_database_table_url"]
        self.wt_schema_next_url = self.init_data["url_init"]["wt_schema_next_url"]
        self.wt_schemas_next_url = self.init_data["url_init"]["wt_schemas_next_url"]
        self.wt_datasource_list_url = self.init_data["url_init"]["wt_datasource_list_url"]
        self.wt_projects_url = self.init_data["url_init"]["wt_projects_url"]
        self.wt_job_delete = self.init_data["url_init"]["wt_job_delete"]
        self.ws_workflow_gen_task_codes_url = self.init_data["url_init"]["ws_workflow_gen_task_codes_url"]
        self.ws_task_instance_url = self.init_data["url_init"]["ws_task_instance_url"]
        self.wt_datasource_list_url = self.init_data["url_init"]["wt_datasource_list_url"]
        self.wt_datasource_create_url = self.init_data["url_init"]["wt_datasource_create_url"]
        self.wt_datasource_delete_url = self.init_data["url_init"]["wt_datasource_delete_url"]
        self.wt_datasource_check_url = self.init_data["url_init"]["wt_datasource_check_url"]
        self.wt_job_url = self.init_data["url_init"]["wt_job_url"]
        self.wt_job_define_url = self.init_data["url_init"]["wt_job_define_url"]

        self.wt_job_config_url = self.init_data["url_init"]["wt_job_config_url"]
        self.wt_job_dag_url = self.init_data["url_init"]["wt_job_dag_url"]
        self.wt_task_define_url = self.init_data["url_init"]["wt_task_define_url"]
        self.wt_task_sink_schema_next_url = self.init_data["url_init"]["wt_task_sink_schema_next_url"]
        self.wt_set_batch_alert_conf_url = self.init_data["url_init"]["wt_set_batch_alert_conf_url"]
        self.wt_set_stream_alert_conf_url = self.init_data["url_init"]["wt_set_stream_alert_conf_url"]
        self.wt_query_alert_url = self.init_data["url_init"]["wt_query_alert_url"]
        self.wt_query_alert_detail_url = self.init_data["url_init"]["wt_query_alert_detail_url"]


        self.batch_task_run_data = self.init_data["batch_run_task_init"]["batch_task_run_data"]
        self.ws_workflow_define_query_data = self.init_data["batch_run_task_init"]["ws_workflow_define_query_data"]
        self.wt_stream_define_query_data = self.init_data["cdc_run_task_init"]["wt_stream_define_query_data"]
        self.wt_batch_incre_task_define_data = self.init_data["batch_create_task_init"]["batch_incre_task_define_data"]
        self.wt_database_table_param = self.init_data["database_init"]["database_table_param"]
        self.res_db_log = str(self.init_data["url_init"]["sys_path"]) + str(self.init_data["url_init"]["res_db_log"])
        self.res_next_schema_log = str(self.init_data["url_init"]["sys_path"]) + str(
            self.init_data["url_init"]["res_next_schema_log"])
        self.create_datasource_json = str(self.init_data["url_init"]["sys_path"]) + str(
            self.init_data["url_init"]["create_datasource_json"])

    def load_db_params(self):
        self.wt_database_list_param = self.init_data["database_init"]["database_list_param"]

    def load_wt_params(self):
        self.wt_integration_job_define = self.init_data["wt_common_config"]["wt_integration_job_define"]
        self.sys_version = self.init_data["wt_common_config"]["sys_version"]
        self.wt_task_config_json = self.init_data["wt_common_config"]["wt_task_config_json"]
        self.wt_task_dag_line = self.init_data["wt_common_config"]["wt_task_dag_line"]
        self.connector_jdbc_mappers_source = self.init_data["connector_jdbc_mappers"]["connector_jdbc_mappers_source"]
        self.connector_jdbc_mappers_sink = self.init_data["connector_jdbc_mappers"]["connector_jdbc_mappers_sink"]
        self.connector_file_mappers = self.init_data["connector_file_mappers"]
        self.connector_cdc_mappers = self.init_data["connector_cdc_mappers"]
        self.mysql_cdc_mapper_source = self.init_data["mysql_cdc_mappers"]["mysql_cdc_mapper_json"]
        self.wt_task_instance_search = self.init_data["wt_task_instance"]["wt_task_instance_search"]
        self.wt_log_detail = self.init_data["url_init"]["wt_log_detail"]
        self.wt_import_task_json = self.init_data["wt_import_task_json"]["wt_import_task_json"]
        self.wt_import_alert_for_fail_task_json = self.init_data["wt_import_task_json"]["wt_import_alert_for_fail_task_json"]
        self.wt_import_transform_single_4method_json = self.init_data["wt_import_task_json"]["wt_import_transform_single_4method_json"]
        self.wt_import_transform_single_dml_customerSql_json = self.init_data["wt_import_task_json"]["wt_import_transform_single_dml_customerSql_json"]
        self.wt_import_transform_single_javaUdf_json = self.init_data["wt_import_task_json"]["wt_import_transform_single_javaUdf_json"]
        self.wt_import_transform_muti_4method_json = self.init_data["wt_import_task_json"]["wt_import_transform_muti_4method_json"]
        self.wt_import_transform_muti_dml_customerSql_json = self.init_data["wt_import_task_json"]["wt_import_transform_muti_dml_customerSql_json"]
        self.wt_import_transform_muti_javaUdf_json = self.init_data["wt_import_task_json"]["wt_import_transform_muti_javaUdf_json"]
        self.wt_batch_task_alert_config_json = self.init_data["wt_common_config"]["wt_batch_task_alert_config_json"]
        self.wt_alert_detail_request_json = self.init_data["wt_common_config"]["wt_alert_detail_request_json"]
        self.wt_stream_task_alert_config_json = self.init_data["wt_common_config"]["wt_stream_task_alert_config_json"]
        self.wt_alert_send_list_json = self.init_data["wt_common_config"]["wt_alert_send_list_json"]
        self.wt_import_mysql_ddl_change_json = self.init_data["wt_import_task_json"]["wt_import_mysql_ddl_change_json"]






    def load_ws_params(self):
        self.ws_batch_task_definition = self.init_data["ws_task_define"]["ws_batch_task_definition"]
        self.ws_stream_task_definition = self.init_data["ws_task_define"]["ws_stream_task_definition"]
        self.ws_task_search_json = self.init_data["ws_task_define"]["ws_task_search_json"]
        self.ws_task_instance_search = self.init_data["ws_task_instance"]["ws_task_instance_search"]
        self.ws_task_run_json = self.init_data["ws_task_run"]["ws_task_run_json"]

    def init_stream_data(self):
        self.cdc_task_run_data = self.init_data["cdc_run_task_init"]["cdc_task_run_data"]
        self.cdc_task_stop_data = self.init_data["cdc_run_task_init"]["cdc_task_stop_data"]
        self.cdc_task_search_data = self.init_data["cdc_run_task_init"]["cdc_task_search_data"]
        self.cdc_task_search_param = self.init_data["cdc_run_task_init"]["cdc_task_search_param"]


    def host_set(self, ip=""):
        """
        替换环境地址: url_init
        :param ip:
        :return:
        """
        current_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(current_dir, 'read_param/url_init')
        with open(file_path, "r") as f:
            j_data = re.sub(r'st\d+:\d+', "{}:12345".format(ip), f.read())

        with open(file_path, "w") as f:
            f.write(j_data)

    def read_files_in_directory(self, directory):
        result = {}
        for root, dirs, files in os.walk(directory):
            if "__pycache__" in dirs:
                dirs.remove("__pycache__")

            for file_name in files:
                file_path = os.path.join(root, file_name)
                try:
                    # 检测文件编码
                    with open(file_path, 'rb') as f:
                        raw_data = f.read()
                        encoding = chardet.detect(raw_data)['encoding']

                    # 使用检测到的编码读取文件
                    with open(file_path, 'r', encoding=encoding) as f:
                        result[file_name] = json.load(f)  # 读取并解析 JSON

                except json.JSONDecodeError as json_err:
                    print(f"Error decoding JSON from file {file_path}: {json_err}")
                except Exception as e:
                    print(f"Error reading file {file_path}: {e}")

        return result

    def red_init_param_file(self):
        """
        读取 int_param/read_param 下全部文件
        :return:
        """
        current_dir = os.path.dirname(os.path.abspath(__file__))

        init_data_dir = os.path.join(current_dir, 'read_param')
        res = self.read_files_in_directory(init_data_dir)

        return res


if __name__ == '__main__':
    da = TaskInit()
    a = da.getdb_test()
    print(a)
    for key in a:
        print(key)
    # data = da.red_init_param_file()
    # print(data)
    # da.host_set("st6")
    # da.host_set("st08")
    # regex = re.compile(r"st.\d:")
    # name = 'fla346s35k_st1:sc32ript'
    # name = regex.sub('st08', name)
    # print(name)
    # da.host_set("st5")
